/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datacore.controller.exceptions.PreexistingEntityException;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import pt.iasd.youthshelter.datamodel.Involvement;
import pt.iasd.youthshelter.datamodel.Activity;
import pt.iasd.youthshelter.datamodel.ActivityParticipation;
import pt.iasd.youthshelter.datamodel.ActivityParticipationPK;
import pt.iasd.youthshelter.datamodel.ActivityParticipation_;
import pt.iasd.youthshelter.datamodel.service.ActivityParticipationController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=ActivityParticipationController.class)
public class ActivityParticipationJpaController implements Serializable, ActivityParticipationController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(ActivityParticipation activityParticipation) throws PreexistingEntityException, Exception {
        if (activityParticipation.getActivityParticipationPK() == null) {
            activityParticipation.setActivityParticipationPK(new ActivityParticipationPK());
        }
        activityParticipation.getActivityParticipationPK().setActivityId(activityParticipation.getActivity().getId());
        activityParticipation.getActivityParticipationPK().setPathfinderId(activityParticipation.getPathfinder().getId());
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Pathfinder pathfinder = activityParticipation.getPathfinder();
            if (pathfinder != null) {
                pathfinder = em.getReference(pathfinder.getClass(), pathfinder.getId());
                activityParticipation.setPathfinder(pathfinder);
            }
            Involvement involvementId = activityParticipation.getInvolvementId();
            if (involvementId != null) {
                involvementId = em.getReference(involvementId.getClass(), involvementId.getId());
                activityParticipation.setInvolvementId(involvementId);
            }
            Activity activity = activityParticipation.getActivity();
            if (activity != null) {
                activity = em.getReference(activity.getClass(), activity.getId());
                activityParticipation.setActivity(activity);
            }
            em.persist(activityParticipation);
            if (pathfinder != null) {
                pathfinder.getActivityParticipationList().add(activityParticipation);
                em.merge(pathfinder);
            }
            if (involvementId != null) {
                involvementId.getActivityParticipationList().add(activityParticipation);
                em.merge(involvementId);
            }
            if (activity != null) {
                activity.getActivityParticipationList().add(activityParticipation);
                em.merge(activity);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findActivityParticipation(activityParticipation.getActivityParticipationPK()) != null) {
                throw new PreexistingEntityException("ActivityParticipation " + activityParticipation + " already exists.", ex);
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(ActivityParticipation activityParticipation) throws NonexistentEntityException, Exception {
        activityParticipation.getActivityParticipationPK().setActivityId(activityParticipation.getActivity().getId());
        activityParticipation.getActivityParticipationPK().setPathfinderId(activityParticipation.getPathfinder().getId());
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            ActivityParticipation persistentActivityParticipation = em.find(ActivityParticipation.class, activityParticipation.getActivityParticipationPK());
            Pathfinder pathfinderOld = persistentActivityParticipation.getPathfinder();
            Pathfinder pathfinderNew = activityParticipation.getPathfinder();
            Involvement involvementIdOld = persistentActivityParticipation.getInvolvementId();
            Involvement involvementIdNew = activityParticipation.getInvolvementId();
            Activity activityOld = persistentActivityParticipation.getActivity();
            Activity activityNew = activityParticipation.getActivity();
            if (pathfinderNew != null) {
                pathfinderNew = em.getReference(pathfinderNew.getClass(), pathfinderNew.getId());
                activityParticipation.setPathfinder(pathfinderNew);
            }
            if (involvementIdNew != null) {
                involvementIdNew = em.getReference(involvementIdNew.getClass(), involvementIdNew.getId());
                activityParticipation.setInvolvementId(involvementIdNew);
            }
            if (activityNew != null) {
                activityNew = em.getReference(activityNew.getClass(), activityNew.getId());
                activityParticipation.setActivity(activityNew);
            }
            activityParticipation = em.merge(activityParticipation);
            if (pathfinderOld != null && !pathfinderOld.equals(pathfinderNew)) {
                pathfinderOld.getActivityParticipationList().remove(activityParticipation);
                pathfinderOld = em.merge(pathfinderOld);
            }
            if (pathfinderNew != null && !pathfinderNew.equals(pathfinderOld)) {
                pathfinderNew.getActivityParticipationList().add(activityParticipation);
                em.merge(pathfinderNew);
            }
            if (involvementIdOld != null && !involvementIdOld.equals(involvementIdNew)) {
                involvementIdOld.getActivityParticipationList().remove(activityParticipation);
                involvementIdOld = em.merge(involvementIdOld);
            }
            if (involvementIdNew != null && !involvementIdNew.equals(involvementIdOld)) {
                involvementIdNew.getActivityParticipationList().add(activityParticipation);
                em.merge(involvementIdNew);
            }
            if (activityOld != null && !activityOld.equals(activityNew)) {
                activityOld.getActivityParticipationList().remove(activityParticipation);
                activityOld = em.merge(activityOld);
            }
            if (activityNew != null && !activityNew.equals(activityOld)) {
                activityNew.getActivityParticipationList().add(activityParticipation);
                em.merge(activityNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                ActivityParticipationPK id = activityParticipation.getActivityParticipationPK();
                if (findActivityParticipation(id) == null) {
                    throw new NonexistentEntityException("The activityParticipation with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(ActivityParticipationPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            ActivityParticipation activityParticipation;
            try {
                activityParticipation = em.getReference(ActivityParticipation.class, id);
                activityParticipation.getActivityParticipationPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The activityParticipation with id " + id + " no longer exists.", enfe);
            }
            Pathfinder pathfinder = activityParticipation.getPathfinder();
            if (pathfinder != null) {
                pathfinder.getActivityParticipationList().remove(activityParticipation);
                em.merge(pathfinder);
            }
            Involvement involvementId = activityParticipation.getInvolvementId();
            if (involvementId != null) {
                involvementId.getActivityParticipationList().remove(activityParticipation);
                em.merge(involvementId);
            }
            Activity activity = activityParticipation.getActivity();
            if (activity != null) {
                activity.getActivityParticipationList().remove(activityParticipation);
                em.merge(activity);
            }
            em.remove(activityParticipation);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }
    
    @Override
    public int destroyAll(Activity activity) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaDelete criteria = builder.createCriteriaDelete(ActivityParticipation.class);
            Root<ActivityParticipation> root = criteria.from(ActivityParticipation.class);
            criteria.where(builder.equal(root.get(ActivityParticipation_.activity), activity));
            Query query = em.createQuery(criteria);
            return query.executeUpdate();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return -1;
    }

    @Override
    public List<ActivityParticipation> findActivityParticipationEntities() {
        return findActivityParticipationEntities(true, -1, -1);
    }

    @Override
    public List<ActivityParticipation> findActivityParticipationEntities(int maxResults, int firstResult) {
        return findActivityParticipationEntities(false, maxResults, firstResult);
    }

    private List<ActivityParticipation> findActivityParticipationEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ActivityParticipation.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public ActivityParticipation findActivityParticipation(ActivityParticipationPK id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(ActivityParticipation.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getActivityParticipationCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ActivityParticipation> rt = cq.from(ActivityParticipation.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
